package com.iyunsir.suit.controller;

import com.iyunsir.common.vo.Result;
import com.iyunsir.suit.entity.Suit;
import com.iyunsir.suit.server.SuitService;
import com.iyunsir.suit.vo.SuitQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/suit")
public class SuitController {
    @Autowired
    private SuitService suitService;

    @GetMapping("/list")
    @ResponseBody
    public Result<Object> getSuitList(SuitQuery param) {
        List<Suit> list = suitService.getSuitList(param);
        Long count = suitService.countSuitList(param);
        return Result.success(list, count);
    }

    @PostMapping("")
    @ResponseBody
    public Result<Object> addSuit(Suit suit) {
        suitService.addSuit(suit);
        return Result.success("新增成功");

    }

    @GetMapping("/add/ui")
    public String toAddUI() {

        return "recommend/recAdd";
    }

    @DeleteMapping("/{ids}")
    @ResponseBody
    public Result<Object> deleteSuitByIds(@PathVariable("ids") String ids) {
        suitService.deleteSuitByIds(ids);
        return Result.success("删除成功！");
    }

    @GetMapping("/{id}")
    public String getSuitById(@PathVariable("id") Integer id, Model model) {
        Suit suit = suitService.getSuitById(id);
        model.addAttribute("suit", suit);
        return "recommend/recEdit";
    }

    @PutMapping("")
    @ResponseBody
    public Result<Object> updateSuit(Suit suit) {
        suitService.updateSuit(suit);
        return Result.success("修改成功!");

    }

    @ResponseBody
    @PostMapping("/upload")
    public Result<Object> upload(MultipartFile file) throws IOException {
        URL url = ClassUtils.getDefaultClassLoader().getResource("");
        Path uploadPath = Paths.get(url.getPath().substring(1) + "static/upload");
        if (Files.notExists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        String fileName = Instant.now().toEpochMilli() + ".jpg";
        Files.copy(file.getInputStream(), Paths.get(uploadPath + File.separator + fileName));
        Map<String, String> data = new HashMap<>(1);
        data.put("file", fileName);
        return Result.success(data, 1L);
    }
}
